#pragma once

#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>

//工具类
class Util{
    public:
        static int ReadLine(int sock,std::string &out)
        {
            char ch = 'x';
            while(ch != '\n'){
                ssize_t s = recv(sock,&ch,1,0);// 从sock中读取一个字符到ch中
                if(s > 0){                 
                    if(ch == '\r'){
                        recv(sock,&ch,1,MSG_PEEK);// MSG_PEEK 窥探下一个字符（不从sock中取走）
                        if(ch == '\n'){
                            // 把\r\n -> \n
                            // 窥探成功读取该字符
                            recv(sock,&ch,1,0);
                        }
                        else{
                            ch = '\n';// \r -> \n
                        }
                    }
                    // 到这有两种情况 1.普通字符 2.\n
                    out.push_back(ch);
                }
                else if(s == 0){
                    return 0;
                }
                else{
                    return -1;
                }
            }
            return out.size();
        }

        static bool CutString(const std::string &target, std::string &sub1_out, std::string &sub2_out, std::string sep)
        {
            size_t pos = target.find(sep);// 查找分割符
            if(pos != std::string::npos){
                sub1_out = target.substr(0,pos);
                sub2_out = target.substr(pos+sep.size());
                return true;
            }
            return false;
        }
};